﻿@model OrderListModel
@inject AdminAreaSettings adminAreaSettings
@inject IStoreService storeService

@using Nop.Services.Stores

@{
    var defaultGridPageSize = adminAreaSettings.DefaultGridPageSize;
    var gridPageSizes = adminAreaSettings.GridPageSizes;
    var stores = storeService.GetAllStores();

    //page title
    ViewBag.Title = T("Admin.Orders").Text;
    //active menu item (system name)
    Html.SetActiveMenuItemSystemName("Orders");
}



<form asp-controller="Order" asp-action="List" method="post">
    <div class="content-header clearfix">
        <h1 class="pull-left">
            @T("Admin.Orders")
        </h1>
        <div class="pull-right">
            <div class="btn-group">
                <button type="button" class="btn btn-success">
                    <i class="fa fa-download"></i>
                    @T("Admin.Common.Export")
                </button>
                <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button type="submit" name="exportxml-all">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportxml-selected">
                            <i class="fa fa-file-code-o"></i>
                            @T("Admin.Common.ExportToXml.Selected")
                        </button>
                    </li>
                    <li class="divider"></li>
                    <li>
                        <button type="submit" name="exportexcel-all">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="exportexcel-selected">
                            <i class="fa fa-file-excel-o"></i>
                            @T("Admin.Common.ExportToExcel.Selected")
                        </button>
                    </li>
                </ul>
            </div>
            <div class="btn-group">
                <button type="button" class="btn bg-purple">
                    <i class="fa fa-file-pdf-o"></i>
                    @T("Admin.Orders.PdfInvoices")
                </button>
                <button type="button" class="btn bg-purple dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                    <span class="sr-only">&nbsp;</span>
                </button>
                <ul class="dropdown-menu" role="menu">
                    <li>
                        <button type="submit" name="pdf-invoice-all">
                            @T("Admin.Orders.PdfInvoices.All")
                        </button>
                    </li>
                    <li>
                        <button type="button" id="pdf-invoice-selected">
                            @T("Admin.Orders.PdfInvoices.Selected")
                        </button>
                    </li>
                </ul>
            </div>
            @await Component.InvokeAsync("AdminWidget", new { widgetZone = "admin_order_list_buttons" })
        </div>
    </div>
    <div class="content">
        <div class="form-horizontal">
            <div class="panel-group">
                <div class="panel panel-default panel-search">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-5">
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="StartDate" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-editor asp-for="StartDate" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="EndDate" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-editor asp-for="EndDate" />
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableWarehouses.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="WarehouseId" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="WarehouseId" asp-items="Model.AvailableWarehouses" />
                                    </div>
                                </div>
                                <div class="form-group">                                    
                                    <div class="col-md-4">
                                        <nop-label asp-for="ProductId" />
                                    </div>
                                    <div class="col-md-8">
                                        <input type="text" id="search-product-name" autocomplete="off" class="form-control" />
                                        <span id="search-product-friendly-name"></span>
                                        <button type="button" id="search-product-clear" class="btn bg-gray" style="display: none; margin-top: 5px;">@T("Admin.Common.Clear")</button>
                                        <input asp-for="ProductId" autocomplete="off" style="display:none;" />
                                        <script type="text/javascript">
                            $(document).ready(function() {
                                $('#search-product-name').autocomplete({
                                    delay: 500,
                                    minLength: 3,
                                    source: '@(Url.Action("ProductSearchAutoComplete"))',
                                    select: function(event, ui) {
                                        $('#@Html.IdFor(model => model.ProductId)').val(ui.item.productid);
                                        $('#search-product-friendly-name').text(ui.item.label);

                                        $('#search-product-clear').show();
                                        return false;
                                    }
                                });

                                //remove button
                                $('#search-product-clear').click(function() {
                                    $('#@Html.IdFor(model => model.ProductId)').val('0');
                                    $('#search-product-friendly-name').text('');
                                    $('#search-product-clear').hide();
                                    return false;
                                });
                            });
                                        </script>
                                    </div>
                                </div>
                                <div class="form-group" @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="OrderStatusIds" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="OrderStatusIds" asp-items="Model.AvailableOrderStatuses" asp-multiple="true" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="PaymentStatusIds" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="PaymentStatusIds" asp-items="Model.AvailablePaymentStatuses" asp-multiple="true" />
                                    </div>
                                </div>
                                <div class="form-group" @(Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="ShippingStatusIds" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="ShippingStatusIds" asp-items="Model.AvailableShippingStatuses" asp-multiple="true" />
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-7">
                                <div class="form-group" @(Model.AvailableStores.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="StoreId" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="StoreId" asp-items="Model.AvailableStores" />
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableVendors.SelectionIsNotPossible() || Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="VendorId" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="VendorId" asp-items="Model.AvailableVendors" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="BillingEmail" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-editor asp-for="BillingEmail" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="BillingLastName" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-editor asp-for="BillingLastName" />
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailableCountries.SelectionIsNotPossible() ? Html.Raw("style=\"display:none\"") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="BillingCountryId" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="BillingCountryId" asp-items="Model.AvailableCountries" />
                                    </div>
                                </div>
                                <div class="form-group" @(Model.AvailablePaymentMethods.SelectionIsNotPossible() || Model.IsLoggedInAsVendor ? Html.Raw("style='display: none;'") : null)>
                                    <div class="col-md-4">
                                        <nop-label asp-for="PaymentMethodSystemName" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-select asp-for="PaymentMethodSystemName" asp-items="Model.AvailablePaymentMethods" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="OrderNotes" />
                                    </div>
                                    <div class="col-md-8">
                                        <nop-editor asp-for="OrderNotes" />
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4">
                                        <nop-label asp-for="GoDirectlyToCustomOrderNumber" />
                                    </div>
                                    <div class="col-md-8">
                                        <div class="input-group input-group-short">
                                            <nop-editor asp-for="GoDirectlyToCustomOrderNumber" />
                                            <span class="input-group-btn">
                                                <button type="submit" id="go-to-order-by-number" name="go-to-order-by-number" class="btn btn-info btn-flat">
                                                    @T("Admin.Common.Go")
                                                </button>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-7 col-md-offset-5">
                                <button type="button" id="search-orders" class="btn btn-primary btn-search">
                                    <i class="fa fa-search"></i>
                                    @T("Admin.Common.Search")
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-body">
                        <div id="orders-grid"></div>

                        <script type="text/javascript">
    $(document).ready(function() {
        $("#orders-grid").kendoGrid({
            dataSource: {
                type: "json",
                transport: {
                    read: {
                        url: "@Html.Raw(Url.Action("OrderList", "Order"))",
                        type: "POST",
                        dataType: "json",
                        data: additionalData
                    }
                },
                schema: {
                    data: "Data",
                    total: "Total",
                    errors: "Errors"
                },
                requestEnd: function (e) {
                    if (e.type == "read") {
                        var response = e.response;
                        if (response) {
                            //store extra data
                            reportAggregates = e.response["ExtraData"];
                        }
                    }
                },
                error: function(e) {
                    display_kendoui_grid_error(e);
                    // Cancel the changes
                    this.cancelChanges();
                },
                pageSize: @(defaultGridPageSize),
                serverPaging: true,
                serverFiltering: true,
                serverSorting: true
            },
            pageable: {
                refresh: true,
                pageSizes: [@(gridPageSizes)],
                @await Html.PartialAsync("_GridPagerMessages")
            },
            editable: {
                confirmation: "@T("Admin.Common.DeleteConfirmation")",
                mode: "inline"
            },
            scrollable: false,
            dataBound: onDataBound,
            columns: [
                {
                    field: "Id",
                    headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                    headerAttributes: { style: "text-align:center" },
                    attributes: { style: "text-align:center" },
                    template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                    width: 50
                }, {
                    field: "CustomOrderNumber",
                    title: "@T("Admin.Orders.Fields.CustomOrderNumber")",
                    width: 80
                },
                @if (!Model.IsLoggedInAsVendor)
                {
                    //a vendor does not have access to this functionality
                    <text>{
                    field: "OrderStatus",
                    title: "@T("Admin.Orders.Fields.OrderStatus")",
                    width: 100,
                    template: '<span class="grid-report-item ' +
                        '# if(OrderStatusId == 10) {# yellow #} #' +
                        '# if(OrderStatusId == 20) {# blue #} #' +
                        '# if(OrderStatusId == 30) {# green #} #' +
                        '# if(OrderStatusId == 40) {# red #} #' +
                        '">#=OrderStatus#</span>'
                },</text>
                }
                {
                    field: "PaymentStatus",
                    title: "@T("Admin.Orders.Fields.PaymentStatus")",
                    width: 150
                },
                @if (!Model.IsLoggedInAsVendor)
                {
                    //a vendor does not have access to this functionality
                    <text>{
                    field: "ShippingStatus",
                    title: "@T("Admin.Orders.Fields.ShippingStatus")",
                    width: 150
                },</text>
                }
                {
                    field: "CustomerEmail",
                    title: "@T("Admin.Orders.Fields.Customer")",
                    width: 250,
                    template: '#=CustomerFullName# (#=CustomerEmail#)'
                },
                {
                    field: "StoreName",
                    hidden: @(stores.Count > 1 ? "false" : "true"),
                    title: "@T("Admin.Orders.Fields.Store")",
                    width: 100
                }, {
                    field: "CreatedOn",
                    title: "@T("Admin.Orders.Fields.CreatedOn")",
                    width: 150,
                    type: "date",
                    format: "{0:G}"
                },
                @if (!Model.IsLoggedInAsVendor)
                {
                    //a vendor does not have access to this functionality
                    <text>{
                    field: "OrderTotal",
                    title: "@T("Admin.Orders.Fields.OrderTotal")",
                    width: 100,
                    footerTemplate: '<div><strong>@T("Admin.Orders.Report.Summary")</strong></div>' +
                        '<div>@T("Admin.Orders.Report.Profit") <span id=\"aggregator-profit-block\"></span></div>' +
                        '<div>@T("Admin.Orders.Report.Shipping") <span id=\"aggregator-shipping-block\"></span></div>' +
                        '<div>@T("Admin.Orders.Report.Tax") <span id=\"aggregator-tax-block\"></span></div>' +
                        '<div>@T("Admin.Orders.Report.Total") <span id=\"aggregator-total-block\"></span></div>'
                },</text>
                }
                {
                    field: "Id",
                    title: "@T("Admin.Common.View")",
                    width: 50,
                    headerAttributes: { style: "text-align:center" },
                    attributes: { style: "text-align:center" },
                    template: '<a class="btn btn-default" href="Edit/#=Id#"><i class="fa fa-eye"></i>@T("Admin.Common.View")</a>'
                }
            ]
        } );
    });
                        </script>

                        <script type="text/javascript">
    var selectedIds = [];
    var reportAggregates = "";

    $(document).ready(function () {
        //search button
        $('#search-orders').click(function () {
            //search
            var grid = $('#orders-grid').data('kendoGrid');
            grid.dataSource.page(1); //new search. Set page size to 1
            //grid.dataSource.read(); we already loaded the grid above using "page" function
            //clear selected checkboxes
            $('.checkboxGroups').attr('checked', false).change();
            selectedIds = [];
            return false;
        });

        $("".concat("#@Html.IdFor(model => model.BillingEmail),",
            "#@Html.IdFor(model => model.BillingLastName),",
            "#@Html.IdFor(model => model.OrderNotes)")).keydown(function (event) {
            if (event.keyCode === 13) {
                $("#search-orders").click();
                return false;
            }
        });

        $("#@Html.IdFor(model => model.GoDirectlyToCustomOrderNumber)").keydown(function(event) {
            if (event.keyCode === 13) {
                $("#go-to-order-by-number").click();
                return false;
            }
        });

        $('#mastercheckbox').click(function () {
            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
        });

        //wire up checkboxes.
        $('#orders-grid').on('change', 'input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]', function (e) {
            var $check = $(this);
            if ($check.is(":checked") == true) {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked == -1) {
                    //add id to selectedIds.
                    selectedIds.push($check.val());
                }
            }
            else {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked > -1) {
                    //remove id from selectedIds.
                    selectedIds = $.grep(selectedIds, function (item, index) {
                        return item != $check.val();
                    });
                }
            }
            updateMasterCheckbox();
        });
    });

    function additionalData() {
        var data = {
            StartDate: $('#@Html.IdFor(model => model.StartDate)').val(),
            EndDate: $('#@Html.IdFor(model => model.EndDate)').val(),
            OrderStatusIds: $('#@Html.IdFor(model => model.OrderStatusIds)').val(),
            PaymentStatusIds: $('#@Html.IdFor(model => model.PaymentStatusIds)').val(),
            ShippingStatusIds: $('#@Html.IdFor(model => model.ShippingStatusIds)').val(),
            StoreId: $('#@Html.IdFor(model => model.StoreId)').val(),
            VendorId: $('#@Html.IdFor(model => model.VendorId)').val(),
            WarehouseId: $('#@Html.IdFor(model => model.WarehouseId)').val(),
            BillingEmail: $('#@Html.IdFor(model => model.BillingEmail)').val(),
            BillingLastName: $('#@Html.IdFor(model => model.BillingLastName)').val(),
            BillingCountryId: $('#@Html.IdFor(model => model.BillingCountryId)').val(),
            PaymentMethodSystemName: $('#@Html.IdFor(model => model.PaymentMethodSystemName)').val(),
            ProductId: $('#@Html.IdFor(model => model.ProductId)').val(),
            OrderNotes: $('#@Html.IdFor(model => model.OrderNotes)').val()
        };
        addAntiForgeryToken(data);
        return data;
    }

    function onDataBound(e) {
        $('#orders-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').each(function () {
            var currentId = $(this).val();
            var checked = jQuery.inArray(currentId, selectedIds);
            //set checked based on if current checkbox's value is in selectedIds.
            $(this).attr('checked', checked > -1);
        });

        updateMasterCheckbox();

        //update order totals summary
        if (reportAggregates != "") {
            for (var key in reportAggregates) {
                $('#aggregator-profit-block').text(reportAggregates['aggregatorprofit']);
                $('#aggregator-shipping-block').text(reportAggregates['aggregatorshipping']);
                $('#aggregator-tax-block').text(reportAggregates['aggregatortax']);
                $('#aggregator-total-block').text(reportAggregates['aggregatortotal']);
            }
        }
    }

    function updateMasterCheckbox() {
        var numChkBoxes = $('#orders-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]').length;
        var numChkBoxesChecked = $('#orders-grid input[type=checkbox][id!=mastercheckbox][class=checkboxGroups]:checked').length;
        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
    }
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

@*export selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Order" asp-action="ExportXmlSelected" method="post" id="export-xml-selected-form">
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-xml-selected-form #selectedIds').val(ids);
            $('#export-xml-selected-form').submit();
            return false;
        });
    });
</script>

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Order" asp-action="ExportExcelSelected" method="post" id="export-excel-selected-form">
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-excel-selected-form #selectedIds').val(ids);
            $('#export-excel-selected-form').submit();
            return false;
        });
    });
</script>

@*Print packaging slips selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
<form asp-controller="Order" asp-action="PdfInvoiceSelected" method="post" id="pdf-invoice-selected-form">
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
</form>

<script type="text/javascript">
    $(document).ready(function () {
        $('#pdf-invoice-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#pdf-invoice-selected-form #selectedIds').val(ids);
            $('#pdf-invoice-selected-form').submit();
            return false;
        });
    });
</script>